var submitBtn = $('#submit'),
	loginBox = $('#loginBox'),loginText = $('#loginText'),
	cancelBtn = $('#cancelBtn'),loginBtn = $('#loginBtn'),loginBottom = $('#loginBottom'),
	confirmBox = $('#confirmBox'), confirmText = $('#confirmText'),
	confirmBtn = $('#confirmBtn'),
	searchBtn = $('#search'), searchBox = $('#searchBox'),searchText = $('#searchText'),
	dialogBtn = $('#dialogBtn'),
	petNumList = $('#petNumber').find(':radio'),
	roomList = $('#roomList').find(':radio');
var petNum = 1,pets = [],openId = null;
var session = '';
var isWxPay = null;
//商品价格
var Price = {
	'0': 260.00,
	'1': 370.00,
	'2': 498.00
}
var data = {
	goodsName: '',
	qty: '',
	price: '',
	userId: '',
	nickname: '',
	phone: '',
	name: ''
};
/**
 * 输入信息检查
 */
var check = function(){
	var reg = /^[\u4e00-\u9fa5 a-zA-Z]+$/;
	//房间选择检查
	data.goodsName = $('#roomList').find('input:checked');
	if(data.goodsName && data.goodsName.length>0){
		data.goodsName = data.goodsName.val();
	}else{
		showMessageAlert('请选择房间类型');
		return false;
	}
	//个人信息检查
	data.name = $('#realname').val().trim();
	if(data.name==''){
		showMessageAlert('请输入您的真实姓名');
		return false;
	}else if(!reg.test(data.name)){
		showMessageAlert('姓名只可为中文或英文');
		return false;
	}
	//var petNumber = $('#petNumber').find('input:checked');
	//if(petNumber && petNumber.length>0){
	//	petNumber = petNumber.val();
	//}else{
	//	showMessageAlert('请选择宠物数量');
	//	return false;
	//}
	//宠物信息检查
	pets = [];
	chp:{
		for(var i=1; i<=petNum; i++){
			var pet = { type: '' };
			// pet.name = $('#petName'+i).val().trim();
			// if(pet.name==''){
			// 	showMessageAlert('请输入第'+i+'只宠物的名字');
			// 	break chp;
			// }
			pet.type = $('#petType'+i).val().trim();
			if(pet.type==''){
				showMessageAlert('请输入宠物品种');
				break chp;
			}else if(!reg.test(pet.type)){
				showMessageAlert('宠物种类只可为中文或英文');
				break chp;
			}
			pets.push(pet);
			// pet.sterile = $('#petSterile'+i).children('input:checked');
			// if(pet.sterile && pet.sterile.length>0){
			// 	pet.sterile = pet.sterile.val();
			// }else {
			// 	showMessageAlert('请选择第'+i+'只宠物的绝育情况');
			// 	break chp;
			// }
		}
		return true;
	}
	return false;
}
/**
 * 设置宠物数量
 */
var setPetNum = function(num){
	petNum = num;
	switch (num){
		case 1:
			$('#pet2').addClass('hide');
			$('#petType2').val('');
			petNumList[0].checked = true;
			petNumList[1].checked = false;
			$(petNumList[1]).parent().addClass('hide');
			break;
		case 2:
			$('#pet2').removeClass('hide');
			$(petNumList[1]).parent().removeClass('hide');
			break;
	}
}
/**
 * 查看订单时提示的房间类型
 */
var setOrderMsg = function(room){
	var str = '';
	switch (room) {
		case '0': str = '单人拼房'; break;
		case '1': str = '单人独立房间'; break;
		case '2': str = '双人套餐'; break;
	}
	searchText.html('您已经购买了吴江宠物自驾游<strong>'+str+'</strong>，祝您和狗狗周末愉快哦。');
}
/**
 * 提交按钮恢复
 */
var setSubmitOn = function(){
	submitBtn.text('确认支付');
	submitBtn.removeClass('dis').on('click',submit);
}
/**
 * 提交按钮置灰 失效
 */
var setSubmitOff = function(str){
	submitBtn.text(str);
	submitBtn.addClass('dis').off('click');
}
/**
 * 支付成功回调
 */
var successCallback = function(id){
	$.ajax({
		type: 'GET',
		url: '/viptail/api/chain/paySuccess?id='+id,
		dataType: 'json',
		success: function(res){
			//alert(JSON.stringify(res));
		}
	})
}
/**
 * 支付失败回调
 */
var failCallback = function(id){
	$.ajax({
		type: 'GET',
		dataType: 'json',
		url: '/viptail/api/chain/payFaild'+'?id='+id,
		success: function(res){
			//alert(JSON.stringify(res));
		}
	})
}
/**
 * 提交信息
 */
var submit = function(){
	//信息填写检查
	if(!check())
		return false;
	//提交按钮不可再次点击提交
	setSubmitOff('正在支付');
	confirmText.html('正在提交，请稍后...');
	confirmBox.show();
	stopScrolling();
	//提交支付操作 提交检查
	for(var i=1; i <= pets.length; i++){
		data['petType'+i] = pets[i-1].type;
	}
	$.ajax({
		type: 'POST',
		url: '/viptail/api/chain/addLiveCommentsList',
		data: data,
		dataType: 'json',
		success: function(res){
			if(res.respCode==0){
				$.ajax({
                    type: 'GET',
                    dataType: 'json',
                    url: '/viptail/api/forward/getUserOpenid?code='+getUrlParam('code'),
                    success: function(res2){
						if(openId==null){
							openId = res2.respDesc;
						}
                        var data2 = {
                            //userId: data.userId,
                            userId: -999,
                            //session: session,
                            tenpayCode: res.entity.tenpayCode,
							ownCode: res.entity.ownCode,
							totalFee: parseInt(data.price*100),
							openId: openId,
						}
						$.ajax({
                            type: 'GET',
                            dataType: 'json',
							url: getAjaxUrl('/dog2/wechatComm/prepay',data2),
							//url: '/dog2/wechatComm/prepay',
							//data: data2,
                            success: function(res3){
                                if(res3.respCode==0){
									confirmText.html('正在支付...');
									/*去支付*/
					                wx.chooseWXPay({
					                    appId: res3.appId,
					                    timestamp: res3.timeStamp,
					                    package: res3.package,
					                    nonceStr: res3.nonceStr,
					                    signType: res3.signType,
					                    paySign: res3.paySign,
					                    success: function () {
											confirmText.html('支付成功！');
											setSubmitOff('已支付');
											setOrderMsg(res.entity.goodsName);
											successCallback(res.entity.id);
					                    },
										fail: function(){
											confirmText.html('支付失败');
											setSubmitOn();
											failCallback(res.entity.id);
										},
					                    cancel: function () {
											confirmText.html('支付已取消');
											setSubmitOn();
											failCallback(res.entity.id);
										},
					                });
								}else{
									showMessageAlert(res3.respDesc,10);
									//confirmBox.hide();
									setSubmitOn();
									failCallback(res.entity.id);
								}
							},
							error: function(){
								showMessageAlert('订单提交出错');
								//confirmBox.hide();
								setSubmitOn();
								failCallback(res.entity.id);
							}
						})
					},
					error: function(){
						showMessageAlert('订单提交出错');
						//confirmBox.hide();
						setSubmitOn();
						failCallback(res.entity.id);
					}
				});
			}else if(res.respCode==1) {
				//检查失败提示
				showMessageAlert(res.respDesc,10);
				//confirmBox.hide();
				setSubmitOn();
				failCallback(res.entity.id);
			}
		},
		error: function(){
			showMessageAlert('订单提交出错');
			//confirmBox.hide();
			setSubmitOn();
		}
	})
}
//去掉radio的默认事件
roomList.on('change',function(e){
	e.preventDefault;
})
petNumList.on('change',function(){
	switch (parseInt($(this).val())){
		case 1:
			petNum = 1;
			$('#pet2').addClass('hide');
			$('#petType2').val('');
			petNumList[0].checked = true;
			petNumList[1].checked = false;
			break;
		case 2:
			petNum = 2;
			$('#pet2').removeClass('hide');
			break;
	}
})
/**
 * 订单查询
 */
searchBtn.on('click',function(){
	searchBox.show();
	stopScrolling();
})
dialogBtn.on('click',function(){
	searchBox.hide();
	restartScrolling();
})

confirmBtn.on('click',function(){
	confirmBox.hide();
	restartScrolling();
})
/**
 * 是否登录
 */
cancelBtn.on('click',function(){
	loginBox.hide();
	submitBtn.text('登录');
	submitBtn.on('click',function(){
		location.href = 'login.html';
	})
})
loginBtn.on('click',function(){
	location.href = 'login.html';
})
/**
 * 初始化
 */
var init = function(){
	data.phone = getUrlParam('phone');
	data.nickname = decodeURIComponent(getUrlParam('nickname'));
	session = getUrlParam('session');
	data.userId =  getUrlParam('userId');
	if(data.userId) {
		$('#phone').val(data.phone);
		$('#nickname').val(data.nickname);
		$.ajax({
			type: 'POST',
			url: '/viptail/api/chain/getQty',
			data: {userId: data.userId},
			dataType: 'json',
			success: function(res){
				if(res.respCode == 0){
					loginBox.hide();
					//商品信息
					$('#roomList>li').each(function(i){
						var count = 0;
						switch (i) {
							case 0: count = res['0'];break;
							case 1: count = res['1'];break;
							case 2: count = res['2'];break;
						}
						if ( count==0 ){
							$(this).children('span:eq(1)').text('已售完');
							$(this).addClass('out');
							$(this).find(':radio').attr('disabled','disabled');
						}else if ( count>0 ) {
							$(this).children('span:eq(1)').text('剩余'+count+'张');
							//添加点击选择商品事件

						}
					})
					//用户已订购 显示已订购信息
					if(res.entity && res.entity.id){
						//订购房间
						roomList[parseInt(res.entity.goodsName)].checked = true;
						roomList.attr('disabled','disabled');
						//订单查询提示
						setOrderMsg(res.entity.goodsName);
						//真实姓名
						$('#realname').val(res.entity.name).attr('readonly','readonly').removeAttr('onfocus onblur');
						//宠物数量
						petNumList.attr('disabled','disabled');
						//宠物类型
						$('#petType1').val(res.entity.petType1).attr('readonly','readonly').removeAttr('onfocus onblur');
						if(res.entity.petType2){
							$('#petType2').val(res.entity.petType2).attr('readonly','readonly').removeAttr('onfocus onblur');
							setPetNum(2);
						}else{
							setPetNum(1);
						}
						//支付按钮置灰
						if(res.entity.status){
							switch (res.entity.status){
								case 50:
									searchText.html('存在未支付订单，请联系客服。');
									setSubmitOff('未支付');
									break;
								case 70:
									setSubmitOff('已支付');
									break;
								default : break;
							}
						}
					}else{
						//是否支持微信支付
						var timer = setInterval(function(){
							if(isWxPay != null){
								clearInterval(timer);
								if (isWxPay == true) {
									submitBtn.on('click',submit);
									//房间选择事件
									$('#roomList').children('li').on('click',function(){
										var r = $(this).find(':radio');
										if(!r[0].disabled)
											r[0].checked = true;
										var n = r.val();
										data.price = Price[n];
										if(n=='0' || n=='1'){
											setPetNum(1);
											data.qty = 1;
										}else if(n=='2'){
											$(petNumList[1]).parent().removeClass('hide');
											data.qty = 2;
										}
									})
								}else {
									submitBtn.on('click',function(){
										showMessageAlert('您的微信版本不支持微信支付，请先升级哦',11);
										setTimeout(function(){
											wx.closeWindow();
										}, 500);
									})
								}
							}
						},10);
					}
				}else {
					showMessageAlert(res.respDesc,11);
				}
				if(res.errResult){
					showMessageAlert(res.errMsg,11);
				}
			},
			error: function(){
				showMessageAlert('数据出错，请联系客服');
			}
		})
	}else{
		//showMessageAlert('查无用户信息，请先登录，正在跳转到登陆页面...',11);
		loginText.removeClass('middle').html('您当前状态为<strong>未登录</strong>，<br>是否跳转登录？');
		loginBottom.removeClass('hide');
		loginBox.show();
		stopScrolling();
	}
}
//微信支付
if(isWechat()){
	$(function(){
		init()
	})
	$.base64.utf8encode = true;
	var wxData = {
		url: $.base64.encode(location.href),
		base64: true
	};
	$.ajax({
		type: 'POST',
		async: false,
		dataType: 'json',
		url: getAjaxUrl('/dog2/wechatComm/weChatConfig',wxData),
		//url: '/dog2/wechatComm/weChatConfig',
		//data: paramCoding(wxData),
		success: function (data) {
			wx.config({
				appId: data.appId,
				timestamp: data.timestamp,
				nonceStr: data.nonceStr,
				signature: data.signature,
				jsApiList: ['chooseWXPay','onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo','onMenuShareQZone']
			});
			if(data.errResult){
				showMessageAlert(data.errMsg,11);
			}
		},
		error: function (data) {
			data = $.parseJSON(data['responseText']);
			showMessageAlert(data['message']);
		},
		cache: false
	});
	//分享
	var imgUrl = 'http://www.viptail.com/shop/dist/img/logo_up_down.png';
	var desc = '6月自驾游 | 带着狗狗看世界，苏州吴江2日游开始报名啦';
	var link = 'http://www.viptail.com/shop/shop.html';
	wx.ready(function () {
		wx.checkJsApi({
			jsApiList: ['chooseWXPay'],
			success: function (res) {
				isWxPay = res['checkResult']['chooseWXPay'];
			}
		});
		//分享到朋友圈
		wx.onMenuShareTimeline({
			title: '小狗在家-'+desc,
			link: link,
			imgUrl: imgUrl
		});
		//分享给朋友
		wx.onMenuShareAppMessage({
			desc: desc,
			link: link,
			imgUrl: imgUrl
		});
		//分享到QQ
		wx.onMenuShareQQ({
			desc: desc,
			link: link,
			imgUrl: imgUrl
		});
		//分享到腾讯微博
		wx.onMenuShareWeibo({
			desc: desc,
			link: link,
			imgUrl: imgUrl
		});
		//分享到腾讯微博
		wx.onMenuShareQZone({
			desc: desc,
			link: link,
			imgUrl: imgUrl
		});
	});
}else{
	loginText.html('请分享此链接至微信并打开，<br>点击登录即可下单');
	loginBox.show();
	stopScrolling();
}